package run.theo.mallorder.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import run.theo.mallcommons.entity.Result;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * project name: IntelliJ IDEA
 * Date: 2022/10/17 21:57
 *
 * @PackageName: run.theo.mallorder.config
 * @ClassName: ExceptionHandlerPage
 * @Author: Theo
 * @Version:
 * @Description:
 */
@Component
public class ExceptionHandlerPage implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        Result data = null;
        if (e instanceof FlowException) {
            data = new Result(-1, "接口被限流了...",null);
        } else if (e instanceof DegradeException) {
            data = new Result(-2, "接口被降级了...",null);
        }
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(data));
    }
}

